﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;
using Cat;
using System.Security.Cryptography;
using MyDBconnection;

namespace Thesis_2
{
    public partial class frmCustomerEntry : Form
    {
        ConnectionString cs = new ConnectionString();
        OdbcCommand cmd = null;
        OdbcConnection con = null;
        OdbcDataReader rdr = null;
        DatabaseConnection dbcon = new DatabaseConnection();
        public frmCustomerEntry()
        {
            this.Load += new EventHandler(frmCustomerEntry_Load);
            InitializeComponent();
            //Tab1 button
            btnRegister.Click += new EventHandler(btnRegister_Click);
            btnNewRecord.Click += new EventHandler(btnNewRecord_Click);
            
            //Tab1 textbox
            txtContact_no.KeyPress += new KeyPressEventHandler(txtContact_no_KeyPress);
            txtAltContactno.KeyPress += new KeyPressEventHandler(txtAltContactno_KeyPress);
            txtContact_no.Validating+=new CancelEventHandler(txtContact_no_Validating);
            txtAltContactno.Validating += new CancelEventHandler(txtAltContactno_Validating);
            txtEmail.Validating += new CancelEventHandler(txtEmail_Validating);
            //Tab2 Button
            btnclear.Click += new EventHandler(btnclear_Click);
            btnupdate.Click += new EventHandler(btnupdate_Click);
            //Tab2 Textbox
            txtContactU.KeyPress += new KeyPressEventHandler(txtContactU_KeyPress);
            txtContactU.Validating += new CancelEventHandler(txtContactU_Validating);
            txtAltU.KeyPress += new KeyPressEventHandler(txtAltU_KeyPress);
            txtAltU.Validating += new CancelEventHandler(txtAltU_Validating);
            txtEmailU.Validating += new CancelEventHandler(txtEmailU_Validating);
            txtsearchuser.TextChanged += new EventHandler(txtsearchuser_TextChanged);
            //Tab2 Grid
            dataGridView1.RowHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataGridView1_RowHeaderMouseClick);
            
        }

        void txtsearchuser_TextChanged(object sender, EventArgs e)
        {
            if (txtsearchuser.Text != "Search Customer Name")
            {
                dbcon.dbconnection();
                dbcon.loadData("SELECT distinct CustomerID,Customername,Address,City,Contactno,AltContactno,Email FROM tblcustomerprofile WHERE Customername LIKE '%" + txtsearchuser.Text + "%'");
                dataGridView1.DataSource = dbcon.tbl;
                dbcon.DBClose();
            }
            else
            {
                GetData();
            }
        }
        void btnupdate_Click(object sender, EventArgs e)
        {
            if (txtCusUDU.Text == "")
            {
                MessageBox.Show("Please Select Customer ID to update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtsearchuser.Focus();
                return;
            }
            if (txtNameU.Text == "")
            {
                MessageBox.Show("Please Select Customer Name to update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtsearchuser.Focus();
                return;
            }
            if (txtNameU.Text == "")
            {
                MessageBox.Show("Please Select Customer Name to update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtsearchuser.Focus();
                return;
            }
            if (txtContactU.Text == "")
            {
                MessageBox.Show("Please Select Customer Contact No. to Update ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtsearchuser.Focus();
                return;
            }
            if (txtAltU.Text == "")
            {
                MessageBox.Show("Please Select Alternate Customer Contact No. to Update ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtsearchuser.Focus();
                return;
            }
            if (txtEmailU.Text == "")
            {
                MessageBox.Show("Please Select Customer Email Address to Update ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtsearchuser.Focus();
                return;
            }
            dbcon.dbconnection();
            dbcon.UpdateData("Update tblcustomerprofile set Customername='" + txtNameU.Text+ "', Address = '" + txtaddressU.Text + "' ,City = '" + txtCityU.Text + "', Contactno = '" + txtContactU.Text + "',AltContactno = '" + txtAltU.Text + "',Email = '"+txtEmailU.Text+"' Where CustomerID ='" + txtCusUDU.Text + "';");
            MessageBox.Show("Update Success", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            resetUp();
            dbcon.DBClose();
            GetData();
        }
        void btnclear_Click(object sender, EventArgs e)
        {
            resetUp();   
        }
        //Tab2 grid
        void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewRow dr = dataGridView1.SelectedRows[0];
            txtCusUDU.Text = dr.Cells[0].Value.ToString();
            txtNameU.Text = dr.Cells[1].Value.ToString();
            txtaddressU.Text = dr.Cells[2].Value.ToString();
            txtCityU.Text = dr.Cells[3].Value.ToString();
            txtContactU.Text = dr.Cells[4].Value.ToString();
            txtAltU.Text = dr.Cells[5].Value.ToString();
            txtEmailU.Text = dr.Cells[6].Value.ToString();
        }
        //Tab2 txtbox Function
        void txtEmailU_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (txtEmail.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtEmailU.Text))
                {
                    MessageBox.Show("Invalid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmailU.SelectAll();
                    e.Cancel = true;
                }
            }
        }
        void txtAltU_Validating(object sender, CancelEventArgs e)
        {
            if (txtAltU.TextLength > 12)
            {
                MessageBox.Show("Only 11 digits are allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtAltU.Focus();
            }
        }
        void txtAltU_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        void txtContactU_Validating(object sender, CancelEventArgs e)
        {
            if (txtContactU.TextLength > 12)
            {
                MessageBox.Show("Only 11 digits are allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContactU.Focus();
            }
        }
        void txtContactU_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        //Tab1 txtbox Function
        void txtContact_no_Validating(object sender, CancelEventArgs e)
        {
            if (txtContact_no.TextLength > 12)
            {
                MessageBox.Show("Only 11 digits are allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContact_no.Focus();
            }
        }
        void txtEmail_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (txtEmail.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtEmail.Text))
                {
                    MessageBox.Show("Invalid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmail.SelectAll();
                    e.Cancel = true;
                }
            }
        }
        void txtAltContactno_Validating(object sender, CancelEventArgs e)
        {
            if (txtAltContactno.TextLength > 12)
            {
                MessageBox.Show("Only 11 digits are allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContact_no.Focus();
            }
        }
        void txtAltContactno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        void txtContact_no_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        //Tab1 Button Function
        
        void btnRegister_Click(object sender, EventArgs e)
        {
            //Error trap with null values
            #region
            if (txtCustomerName.Text == "")
            {
                MessageBox.Show("Please enter Customer Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCustomerName.Focus();
                return;
            }
            if (txtAddress.Text == "")
            {
                MessageBox.Show("Please enter Customer address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtAddress.Focus();
                return;
            }
            if (txtCity.Text == "")
            {
                MessageBox.Show("Please enter City", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCity.Focus();
                return;
            }
            if (txtContact_no.Text == "")
            {
                MessageBox.Show("Please enter Contact number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtContact_no.Focus();

                return;
            }
            if (txtAltContactno.Text == "")
            {
                MessageBox.Show("Please enter Alternate Contact Number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtAltContactno.Focus();

                return;
            }
            if (txtEmail.Text == "")
            {
                MessageBox.Show("Please enter Customer Email Adrress", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmail.Focus();
                return;
            }
            #endregion //
            try
            {
                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string ct = "Select Customername from tblcustomerprofile where Customername='" + txtCustomerName.Text + "'";
                cmd = new OdbcCommand(ct);
                cmd.Connection = con;
                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    MessageBox.Show("Customer Name Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtCustomerName.Text = "";
                    txtCustomerName.Focus();

                    if ((rdr != null))
                    {
                        rdr.Close();
                    }
                    return;
                }
                con = new OdbcConnection(cs.DBConn);
                con.Open();
                string cb = "Insert into tblcustomerprofile(CustomerID,Customername,Address,City,Contactno,AltContactno,Email) VALUES ('" + txtCustomerID.Text + "','" + txtCustomerName.Text + "','" + txtAddress.Text + "','" + txtCity.Text + "','" + txtContact_no.Text + "','" + txtAltContactno.Text + "','" + txtEmail.Text + "')";
                cmd = new OdbcCommand(cb);
                cmd.Connection = con;
                cmd.ExecuteReader();
                con.Close();
                MessageBox.Show("Successfully Registered", "Customer", MessageBoxButtons.OK, MessageBoxIcon.Information);
                reset();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);



            }



        }      
        void btnNewRecord_Click(object sender, EventArgs e)
        {
            reset();
            autoid();
        }
        //Auto Id and Reset
        public void autoid()
        {
            txtCustomerID.Text = "CID-" + GetUniqueKey(4);
        }
        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[62];
            chars = "123456789".ToCharArray();
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }      
        void reset()
        {
            txtCustomerName.Text = "";
            txtAddress.Text = "";
            txtCity.Text = "";
            txtEmail.Text = "";
            txtAltContactno.Text = "";
            txtContact_no.Text = "";

        }
        void resetUp()
        {
            txtCusUDU.Text = null;
            txtNameU.Text = "";
            txtaddressU.Text = "";
            txtCityU.Text = "";
            txtContactU.Text = "";
            txtAltU.Text = "";
            txtEmailU.Text = "";

        }
        public void GetData()
        {
            dbcon.dbconnection();
            dbcon.loadData("Select distinct CustomerID,Customername,Address,City,Contactno,AltContactno,Email from tblcustomerprofile ");
            dataGridView1.DataSource = dbcon.tbl;
            dbcon.DBClose();
        
        }
        void frmCustomerEntry_Load(object sender, EventArgs e)
        {
            autoid();
            GetData();
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }

    }
}
